#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  dump_contents.py
#  description

#  Created by zhouzongli633 on 2020/8/25 3:18 下午.
#  Copyright ©Intellectus All rights reserved.

import datetime
import os
import sys
import django

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
if CURRENT_DIR not in sys.path:
    sys.path.insert(0, CURRENT_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NICU2HOME.settings')
django.setup()

from Admin.models import DBDumpRecord
from Common.Storage_Blob_Manager import StorageManage
from Common.logger import app_log
from NICU2HOME import settings


def dump_mysql():
    try:
        start_time = datetime.datetime.now()
        app_log.info("settings.DATABASES:{}".format(settings.DATABASES))
        app_log.info("start backup database....")

        app_log.info("tables:EducationCategory education_feeds Hospital tag source")
        backup_path = settings.SQL_DUMP_BACKUP_PATH
        db_host = settings.DATABASES['default']['HOST']
        db_port = settings.DATABASES['default']['PORT']
        db_user = settings.DATABASES['default']['USER']
        db_passwd = settings.DATABASES['default']['PASSWORD']
        db_database = settings.DATABASES['default']['NAME']

        execulte_time = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
        backup = f"{backup_path}/{execulte_time}.sql"
        cmd = f'{settings.SQL_DUMP_PATH} -u{db_user} -h {db_host} -P{db_port} -p{db_passwd} {db_database} ' \
              f'EducationCategory education_feeds Hospital tag source > {backup}'
        app_log.info("cmd:{}".format(cmd))
        ret = os.system(cmd)
        app_log.info("execute ret:{}".format(ret))

        # upload to Storage
        with open(backup, 'rb') as file:
            manager = StorageManage()
            file_name = f"db_dump_file/{execulte_time}.sql"
            file_url = "{}/{}/{}".format(settings.STORAGE_ACCOUNT_URL, settings.STORAGE_CONTAINER_NAME, file_name)
            app_log.info(backup)
            app_log.info(file_url)
            manager.upload_file(file_data=file, file_name=file_name, content_type='text/x-sql')
            cost_time = datetime.datetime.now() - start_time
            r = DBDumpRecord(
                file_path=backup,
                file_url=file_url,
                cost_time=cost_time.total_seconds()
            )
            r.save()
            app_log.info("backup database success...")
    except Exception as ex:
        app_log.info("backup database failure...")
        app_log.exception(ex)
        raise ex


if __name__ == "__main__":
    dump_mysql()
